<template>
  <!--	<up-popup mode="right" :customStyle="{width: '100vw'}" :show="show">-->
  <up-navbar title="添加成员" :autoBack="false" placeholder @leftClick="close"></up-navbar>


  <view class="selection-tabs">
    <view class="tab-item" @click="switchTab('contact')" :class="{ 'active': activeTab === 'contact' }">
      <view class="tab-icon">
        <up-icon name="account" :color="activeTab === 'contact' ? '#fff' : '#666'" size="21"></up-icon>
      </view>
      <view class="tab-text">
        按联系人
      </view>
    </view>
    <view v-if="ShowHide" class="tab-item" :class="{ 'active': activeTab === 'structure' }"
      @click="switchTab('structure')">
      <view class="tab-icon">
        <up-icon name="grid" :color="activeTab === 'structure' ? '#fff' : '#666'" size="21"></up-icon>
      </view>
      <view class="tab-text">
        按架构选
      </view>
    </view>
  </view>

  <!-- 搜索 -->
  <view style="margin:  0 24rpx; background-color: #fff;">
    <up-search @search="reloadList" @clear="reloadList" :showAction="false" clearabled placeholder="搜索"
      v-model="keyword" shape="square"></up-search>
  </view>
  <view class="list-box">
    <!-- 列表 -->
    <up-list :style="listHeightStylePage">
      <mescroll-uni ref="mescrollRef" :top="listHeightStyle.top" bottom="120rpx" @init="mescrollInit"
        @down="downCallback" @up="upCallback" :up="upOption">
        <up-list-item v-for="item in userList" :key="item.id" style="padding: 0 20rpx;">
          <view class="list-item" @click="removeAndAdd(item)">
            <view class="check">
              <up-checkbox usedAlone :checked="setChecked(item)" @change="removeAndAdd(item)"></up-checkbox>
            </view>
            <view class="img" style="width: 72rpx; height: 72rpx;">
              <up-image :src="setUserImg(item)" width="100%" height="100%" radius="10rpx">
                <template #error>
                  <text>{{ showUserName(item.username) }}</text>
                </template>
              </up-image>
            </view>
            <view>
              {{ item.username }} {{ item.username_en }}
            </view>
          </view>
        </up-list-item>
      </mescroll-uni>
    </up-list>
  </view>


  <!-- 底部选中 -->
  <view class="select-container">
    <view class="select-left">
      <text>已选择（{{ selection?.length }}）:</text>
    </view>
    <scroll-view class="scrollContainer" scroll-x>
      <view style="display: flex; width: 100%;" @click="selectedShow = true">
        <view v-for="item in selection" :key="item.id" class="select-item">
          <up-image :src="setUserImg(item)" width="100%" height="100%" radius="10rpx">
            <template #error>
              <text>{{ showUserName(item.username) }}</text>
            </template>
          </up-image>
        </view>
      </view>
    </scroll-view>
    <view class="select-right">
      <up-button @click="submit" :customStyle="{ border: 'none', width: '102rpx', height: '52rpx' }"
        :disabled="selection?.length == 0" type="primary" text="确定"></up-button>
    </view>
  </view>


  <!-- 移除弹出框 -->
  <up-popup :show="selectedShow" @close="selectedShow = fasle">
    <view class="popup-header">
      <view @click="selectedShow = false">
        <up-icon :size="18" bold name="close"></up-icon>
      </view>
      <view style="font-weight: 500;">已选择({{ selection?.length }})</view>
      <view @click="selectedShow = false">确定</view>
    </view>
    <view class="popup-content">
      <up-list height="600rpx">
        <up-list-item v-for="item in selection" :key="item.id" style="padding: 0 20rpx;">
          <view class="list-item" @click="removeAndAdd(item)">
            <view class="check">
              <up-checkbox usedAlone :checked="setChecked(item)"></up-checkbox>
            </view>
            <view class="img" style="width: 64rpx; height: 64rpx;">
              <up-image :src="setUserImg(item)" width="100%" height="100%" radius="10rpx">
                <template #error>
                  <text>{{ showUserName(item.username) }}</text>
                </template>
              </up-image>
            </view>
            <view>
              {{ item.username }} {{ item.username_en }}
            </view>
            <view class="del">
              <up-button type="primary" size="mini" :hairline="false" @click="removeAndAdd(item)" text="移除"></up-button>
            </view>
          </view>
        </up-list-item>
      </up-list>
    </view>
  </up-popup>

  <!--	</up-popup>-->
</template>

<script>
import { chatApi } from '@/apis/cloud/chat';
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
import { getCurrentInstance } from "vue";
const AvaterBaseUrl = "https://cloud.mfarmers.com/dist/interface/public/upload/avatar/";
export default {
  name: "MemberPicker",
  props: {
    // userInfo: {
    // 	type: Object
    // }
  },
  mixins: [MescrollMixin],
  data () {
    return {
      upOption: {
        page: {
          size: 20 // 每页数据的数量,默认10
        },
        noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
        empty: {
          tip: '已经到底了'
        }
      },
      show: false,
      selectedShow: false,
      currentData: [],
      selection: [],
      userList: [],
      pageSize: 20,
      pageNum: 1,
      total: 0,
      keyword: '',
      userInfo: {},
      source: '',
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      topHeight: 0,
      andaddpersonnel: null,
      activeTab: 'contact',
      listHeightStylePage: {}, // 动态高度
      ShowHide: true
    };
  },
  onLoad (value) {
    this.ShowHide = value.ShowHide == 'true' ? true : false
  },
  // 页面销毁前
  onUnload () {

  },

  created () {
    let that = this
    const instance = getCurrentInstance().proxy;
    const eventChannel = instance.getOpenerEventChannel();
    eventChannel.on('groupchat', async function (data) {
      uni.showLoading({
        title: '加载中....'
      });
      that.selection = JSON?.parse(data?.imgheadList)
      that.userInfo = JSON?.parse(data.userInfo)
      that.source = data.source

      that.getList();
      uni.hideLoading()
    })


    // #ifdef H5
    this.listHeightStylePage = {
      height: `${window.innerHeight - 191}px`,
    };
    // #endif 

    // #ifdef APP-PLUS 
    let app = uni.getSystemInfoSync();
    this.listHeightStylePage = {
      height: `${app.windowHeight - 212}px`,
    };
    // #endif 

    this.calculateListHeight()
  },
  mounted () {

  },

  methods: {
    switchTab (tab) {
      let that = this
      if (tab === 'contact') { }
      else {
        uni.navigateTo({
          url: `/components/OrgPicker/Grouporganization?overlay=false&entry=component&VisibleandHidden=true&title=选择联系人&type=user`,
          success: function (res) {
            res.eventChannel.emit('MenberPicker', {
              imgheadList: JSON.stringify(that.selection)
            })
          }
        });
      }
    },
    calculateListHeight () {
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        top: '326rpx'
      };
      // #endif

      // #ifdef H5
      this.listHeightStyle = {
        top: '265rpx'
      };
      // #endif
    },
    mescrollInit (mescroll) {
      this.mescroll = mescroll;
    },
    /*上拉加载的回调*/
    upCallback (page) {
      this.pageNum = page.num; // 页码, 默认从1开始
      this.pageSize = page.size; // 页码, 默认从1开始
      this.getList();
    },
    /*若希望重新加载列表,只需调用此方法即可(内部会自动page.num=1,再主动触发up.callback)*/
    reloadList () {
      this.userList = [];
      this.mescroll.resetUpScroll();
    },
    open (data) {
      this.show = true;
      this.selection = JSON.parse(data);
      this.getList();
    },
    close () {
      uni.navigateBack();
    },
    submit () {
      uni.navigateBack();
      if (this.source == "CreateGroup") {
        uni.$emit('CreateGroupMemberPicker', JSON.stringify(this.selection))
      } else if (this.source == "groupchat") {
        uni.$emit('groupchatMemberPicker', JSON.stringify(this.selection))
      }
      // this.$emit('ok', JSON.stringify(this.selection));
      // this.show = false;
    },
    setUserImg (item) {
      return AvaterBaseUrl + item.phone + '.jpg'
    },
    // 名称超长处理
    showUserName (username) {
      if (username && username.length > 2) {
        return username.substr(1, 2);
      } else {
        return username;
      }
    },
    // 是否选中
    setChecked (event) {
      const findIndex = this.selection?.findIndex(item => item.id == event.id)
      if (findIndex != -1) {
        return true
      } else {
        return false
      }
    },
    // 移除
    removeAndAdd (itemOrArray) {
      // console.log('item',item);
      
      // const findIndex = this.selection.findIndex(i => item.id == i.id);
      // if (findIndex != -1) {
      //   this.selection.splice(findIndex, 1);
      // } else {
      //   this.selection.push(item);
      // }

      const items = Array.isArray(itemOrArray) ? itemOrArray : [itemOrArray];

      items.forEach(item => {
        const findIndex = this.selection.findIndex(i => item.id === i.id);
        if (findIndex !== -1) {
          // 已存在则移除
          this.selection.splice(findIndex, 1);
        } else {
          // 不存在则加入，同时过滤掉重复
          this.selection.push(item);
          this.selection = [...new Map(this.selection.map(i => [i.cloud_worker_id || i.id, i])).values()];
        }
      });

      console.log('当前 selection', this.selection);

    },
    // 用户列表
    async getList () {
      let token = uni.getStorageSync('token')
      // composition上拉加载  compositionupdate下拉刷新
      const params = {
        'data[keywords]': this.keyword,
        'data[pageSize]': this.pageSize,
        'data[page]': this.pageNum,
        url: 'index.php/users/Member/getList'
      }

      const msg = await chatApi(this?.userInfo?.token || token, params);

      if (msg.code === 200) {
        if (this.pageNum === 1) {
          this.userList = msg.data.data;
        } else {
          msg.data.data.forEach(item => {
            this.userList.push(item)
          })
        }
        this.total = msg.data.total;

        this.mescroll.endByPage(msg.data.data.length, msg.data.total);
      } else {
        this.mescroll.endErr()
      }

    },
  }
};
</script>

<style lang="scss" scoped>
.list-item {
  position: relative;
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 0.5px solid #ddd;

  .check {
    margin-right: 10rpx;
  }

  .img {
    margin-right: 24rpx;

    text {
      display: inline-block;
      width: 100%;
      height: 100;
      border-radius: 10rpx;
      color: #fff;
      font-size: 26rpx;
      text-align: center;
      line-height: 72rpx;
      background-color: #3D85FC;
    }
  }

  .del {
    position: absolute;
    right: 10rpx;
    top: 50%;
    transform: translateY(-50%);
  }
}

.select-container {
  position: fixed;
  box-sizing: border-box;
  bottom: 0;
  padding: 20rpx 20rpx 40rpx 20rpx;
  width: 100vw;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #E1E3E5;

  .scrollContainer {
    width: 57%;
  }

  .select-left {
    font-size: 26rpx;
    width: 25%;
  }

  .select-right {
    flex: 1;
  }
}

.select-item {
  width: 60rpx;
  height: 60rpx;
  margin-right: 6rpx;
  flex-shrink: 0;

  text {
    display: inline-block;
    width: 100%;
    height: 100;
    border-radius: 10rpx;
    color: #fff;
    font-size: 20rpx;
    text-align: center;
    line-height: 60rpx;
    background-color: #3D85FC;
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 32rpx;
  padding: 30rpx;
}

.popup-content {}

.selection-tabs {
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  margin-bottom: 10rpx;

  .tab-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10rpx 10rpx;
    border-radius: 20rpx;
    transition: all 0.3s ease;

    &.active {
      background-color: #3D85FC;

      .tab-text {
        color: #fff;
      }
    }

    .tab-icon {
      width: 40rpx;
      height: 40rpx;
      margin-bottom: 8rpx;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .tab-text {
      font-size: 24rpx;
      color: #666;
    }
  }
}
</style>
